import classNames from "classnames";
import React, {
  createContext,
  CSSProperties,
  FC,
  FunctionComponentElement,
  useCallback,
  useState,
} from "react";
import { MenuItemProps } from "./MenuItem";

interface MenuProps {
  defaultIndex?: number;
  onSelect?: (num: number) => void;
  className?: string;
  style?: CSSProperties;
}

interface menuContextProps {
  key: number;
  chioceItem?: (num: number) => void;
}
export const MenuContext = createContext<menuContextProps>({ key: 0 });

const Menu: FC<MenuProps> = (props) => {
  const { defaultIndex, className, style, children, onSelect, ...restProps } =
    props;
  const calssnames = classNames("menu", {});
  const [activeKey, setActiveKey] = useState(defaultIndex);
  const handleClick = useCallback((num: number) => {
    setActiveKey(num);
    onSelect?.(num);
  }, []);
  const contextValue: menuContextProps = {
    key: activeKey ? activeKey : 0,
    chioceItem: handleClick,
  };
  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const element = child as React.FunctionComponentElement<MenuItemProps>;
      if (element?.type?.name === "MenuItem") {
        return React.cloneElement(element, {
          itemkey: index,
        });
      } else {
        console.warn("内容不是menuItem");
        throw new Error("内容不是menuItem");
      }
    });
  };

  const renderChild = React.Children.map(children, (child, index) => {
    const element = child as FunctionComponentElement<MenuItemProps>;
    return React.cloneElement(element, {
      itemkey: index,
    });
  });

  return (
    <ul className={calssnames} style={style}>
      <MenuContext.Provider value={contextValue}>
        {renderChildren()}
      </MenuContext.Provider>
    </ul>
  );
};

export default Menu;
